package com.jxsd.edu.cn.tools;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import com.jxsd.edu.cn.tools.DbTool;

public class ResultBean<T> implements ResultHandler<T>{

	private String parseMethodName(String columnName){
		String temp = "set";
		temp+=columnName.substring(0, 1).toUpperCase();
		temp+=columnName.substring(1);
		return temp;
	}

	@SuppressWarnings("unchecked")
	public T handler(String sql,Object[] params,Class<?> clazz) throws Exception 
	{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		T t = (T) clazz.newInstance();
		try {
			conn = DbTool.getConnection();
			stmt = conn.prepareStatement(sql);
			
			if(params!=null)
			{
				for(int i=0;i<params.length;i++)
				{
					stmt.setObject(i+1, params[i]);
				}
			}
			
			rs = stmt.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			if(rs.next()){
				Method method = null;
				for(int i=1;i<=rsmd.getColumnCount();i++){
					method = clazz.getMethod(parseMethodName(rsmd.getColumnLabel(i)),new Class[]{rs.getObject(i).getClass()});
					method.invoke(t, new Object[]{rs.getObject(i)});
				}
			}
		} finally{
			DbTool.close(stmt, conn, rs);
		}
		return t;
	}
}